<?php
/**
 *
 */

namespace app\vote\model;


use think\Model;

class Vote extends Model
{

    protected $autoWriteTimestamp = true;
    /**
     * 添加投票
     * @param string $title 标题
     * @param array $optionList 选项数组
     * array(
            array('option_title'=>'选项标题'),
            array('option_title'=>'选项标题'),
            ……
     * )
     * @return bool
    */
    public function addVote($title,$optionList = array()){
        $data['title'] = $title;
        $this->startTrans();
        $voteId = $this->save($data);
        if(empty($voteId)){
            $this->rollback();
            return false;
        }
        $voteId = $this->getLastInsID();
        //添加投票选项
        foreach ($optionList as & $item){
            $item['vote_id'] = $voteId;
        }
        $voteOptionModel = new VoteOption();
        if(!$voteOptionModel->saveAll($optionList)){
            $this->rollback();
            return false;
        }
        $this->commit();
        return true;
    }

    /**
     * 获取vote列表（未分页）
    */
    public function getVoteList(){
        $sql = "SELECT
	vote.vote_id,
	vote.title,
	vote.update_time,
	COUNT(vote_option.vote_option_id) AS option_count
FROM
	vote
LEFT JOIN vote_option ON vote_option.vote_id = vote.vote_id
AND vote_option.`status` = 1
WHERE
	vote.`status` = 1
GROUP BY
	vote.vote_id";
        return $this->query($sql);
    }

    /**
     * 获取投票信息及选项
     * @param int $voteId
     * @return array
    */
    public function getInfo($voteId){
        $vote = $this->get($voteId);
        $voteOptionModel = new VoteOption();
        $vote['option_list'] = $voteOptionModel->where(array('vote_id' => $voteId))->select();
        return $vote;
    }
}